""""3.求一组数的第二小的数。用分治法解决"""
def merge_sort(arr):
    """
    使用分治法实现归并排序
    """
    if len(arr) <= 1:
        return arr

    # 分治：将数组分成两半
    mid = len(arr) // 2
    left_half = arr[:mid]
    right_half = arr[mid:]

    # 递归排序两半
    left_sorted = merge_sort(left_half)
    right_sorted = merge_sort(right_half)

    # 合并两个已排序的子数组
    return merge(left_sorted, right_sorted)


def merge(left, right):
    """
    合并两个已排序的数组
    """
    result = []
    i = j = 0

    # 比较两个数组的元素，按顺序合并
    while i < len(left) and j < len(right):
        if left[i] <= right[j]:
            result.append(left[i])
            i += 1
        else:
            result.append(right[j])
            j += 1

    # 添加剩余元素
    result.extend(left[i:])
    result.extend(right[j:])

    return result


# 测试归并排序
def test_merge_sort():
    arr = [38, 27, 43, 3, 9, 82, 10]
    print(f"原始数组: {arr}")
    sorted_arr = merge_sort(arr)
    print(f"排序后数组: {sorted_arr}")
    print()


test_merge_sort()